package utility

import (
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/gogf/gf/v2/util/grand"
	"github.com/yitter/idgenerator-go/idgen"
)

type uIdGenerator struct {
	generator *idgen.DefaultIdGenerator
}

var IdGenerator = uIdGenerator{}

func (u *uIdGenerator) Init(workerId ...uint16) {
	var id uint16
	if len(workerId) > 0 && workerId[0] > 0 {
		id = workerId[0]
	} else {
		id = gconv.Uint16(grand.N(50000, 60000))
	}
	IdGenerator.generator = idgen.NewDefaultIdGenerator(idgen.NewIdGeneratorOptions(id))
}

func (u *uIdGenerator) Get() int64 {
	return u.generator.NewLong()
}

func (u *uIdGenerator) ParseId(id int64) *gtime.Time {
	return gtime.NewFromTimeStamp(id>>(u.generator.Options.WorkerIdBitLength+u.generator.Options.SeqBitLength) + u.generator.Options.BaseTime)
}
